/**
 * 监测站点管理系统 Service
 * 
 * 包含三个核心服务：
 * 1. StationTypeService - 测站类型管理服务
 * 2. StationInfoService - 测站编码管理服务  
 * 3. MonitoringDataService - 监测数据管理服务
 * 
 * @author: [开发者名称]
 * @date: [创建日期]
 */

import { Provide ,Inject} from '@midwayjs/decorator';
import { InjectEntityModel, InjectDataSource } from '@midwayjs/typeorm';
import { Repository, Like, Between, FindManyOptions, MoreThanOrEqual, LessThanOrEqual, DataSource, In, EntityManager } from 'typeorm';
import { StationType, StationInfo, MonitoringData } from '../entity/stationManage.entity';
import {
    CreateStationTypeDTO,
    UpdateStationTypeDTO,
    QueryStationTypeDTO,
    StationTypeResponseDTO,
    CreateStationInfoDTO,
    UpdateStationInfoDTO,
    QueryStationInfoDTO,
    StationInfoResponseDTO,
    CreateMonitoringDataDTO,
    UpdateMonitoringDataDTO,
    QueryMonitoringDataDTO,
    MonitoringDataResponseDTO,
    PageResultDTO,
    DataStatisticsDTO
} from '../dto/stationManage.dto';

/**
 * 自定义业务异常类
 */
export class BusinessException extends Error {
    constructor(message: string, public code: string = 'BUSINESS_ERROR') {
        super(message);
        this.name = 'BusinessException';
    }
}

/**
 * 测站类型管理服务
 */
@Provide()
export class StationTypeService {
    @InjectEntityModel(StationType)
    stationTypeRepository: Repository<StationType>;

    @InjectDataSource()
    dataSource: DataSource;

    /**
     * 创建测站类型
     */
    async create(createDto: CreateStationTypeDTO): Promise<StationTypeResponseDTO> {
        // 检查编码是否已存在
        const existingType = await this.findByCode(createDto.stationTypeCode);
        if (existingType) {
            throw new BusinessException(`测站类型编码 ${createDto.stationTypeCode} 已存在`, 'STATION_TYPE_CODE_EXISTS');
        }

        const entity = this.stationTypeRepository.create(createDto);
        const savedEntity = await this.stationTypeRepository.save(entity);
        return this.toResponseDTO(savedEntity);
    }

    /**
     * 批量导入测站类型 - 修复版本（使用Repository的manager）
     */
    async batchImport(stationTypeList: CreateStationTypeDTO[]): Promise<StationTypeResponseDTO[]> {
        // 验证输入数据
        if (!stationTypeList || stationTypeList.length === 0) {
            throw new BusinessException('导入数据不能为空', 'IMPORT_DATA_EMPTY');
        }

        // 检查重复的测站类型编码
        /* const stationTypeCodes = stationTypeList.map(item => item.stationTypeCode);
        const duplicateCodes = stationTypeCodes.filter((code, index) => stationTypeCodes.indexOf(code) !== index);
        if (duplicateCodes.length > 0) {
            throw new BusinessException(`导入数据中存在重复的测站类型编码: ${duplicateCodes.join(', ')}`, 'DUPLICATE_STATION_TYPE_CODE');
        }

        // 检查数据库中是否已存在
        const existingTypes = await this.stationTypeRepository
            .createQueryBuilder('stationType')
            .where('stationType.stationTypeCode IN (:...codes)', { codes: stationTypeCodes })
            .getMany(); */

        /*  if (existingTypes.length > 0) {
             const existingCodes = existingTypes.map(type => type.stationTypeCode);
             throw new BusinessException(`数据库中已存在测站类型编码: ${existingCodes.join(', ')}`, 'STATION_TYPE_CODE_EXISTS');
         } */

        // 方案1：使用Repository的manager进行事务
        return await this.stationTypeRepository.manager.transaction(async (transactionalEntityManager: EntityManager) => {
            const repository = transactionalEntityManager.getRepository(StationType);
            const entities = repository.create(stationTypeList);
            const savedEntities = await repository.save(entities);
            return savedEntities.map(entity => this.toResponseDTO(entity));
        });
    }

    /**
     * 批量导入测站类型 - 备选方案（不使用事务）
     */
    async batchImportAlternative(stationTypeList: CreateStationTypeDTO[]): Promise<StationTypeResponseDTO[]> {
        // 验证输入数据
        if (!stationTypeList || stationTypeList.length === 0) {
            throw new BusinessException('导入数据不能为空', 'IMPORT_DATA_EMPTY');
        }

        // 检查重复的测站类型编码
        const stationTypeCodes = stationTypeList.map(item => item.stationTypeCode);
        const duplicateCodes = stationTypeCodes.filter((code, index) => stationTypeCodes.indexOf(code) !== index);
        if (duplicateCodes.length > 0) {
            throw new BusinessException(`导入数据中存在重复的测站类型编码: ${duplicateCodes.join(', ')}`, 'DUPLICATE_STATION_TYPE_CODE');
        }

        // 检查数据库中是否已存在
        const existingTypes = await this.stationTypeRepository
            .createQueryBuilder('stationType')
            .where('stationType.stationTypeCode IN (:...codes)', { codes: stationTypeCodes })
            .getMany();

        /*  if (existingTypes.length > 0) {
             const existingCodes = existingTypes.map(type => type.stationTypeCode);
             throw new BusinessException(`数据库中已存在测站类型编码: ${existingCodes.join(', ')}`, 'STATION_TYPE_CODE_EXISTS');
         } */

        // 直接使用Repository批量保存
        try {
            const entities = this.stationTypeRepository.create(stationTypeList);
            const savedEntities = await this.stationTypeRepository.save(entities);
            return savedEntities.map(entity => this.toResponseDTO(entity));
        } catch (error) {
            throw new BusinessException(`批量导入失败: ${error.message}`, 'BATCH_IMPORT_FAILED');
        }
    }

    /**
     * 根据ID查询测站类型
     */
    async findById(id: string): Promise<StationTypeResponseDTO | null> {
        const entity = await this.stationTypeRepository.findOne({ where: { id } });
        return entity ? this.toResponseDTO(entity) : null;
    }

    /**
     * 根据编码查询测站类型
     */
    async findByCode(stationTypeCode: string): Promise<StationTypeResponseDTO | null> {
        const entity = await this.stationTypeRepository.findOne({
            where: { stationTypeCode }
        });
        return entity ? this.toResponseDTO(entity) : null;
    }

    /**
     * 分页查询测站类型
     */
    async findPage(queryDto: QueryStationTypeDTO): Promise<PageResultDTO<StationTypeResponseDTO>> {
        const { pageNum = 1, pageSize = 10, ...searchParams } = queryDto;

        const where: any = {};
        if (searchParams.stationTypeCode) {
            where.stationTypeCode = Like(`%${searchParams.stationTypeCode}%`);
        }
        if (searchParams.stationTypeName) {
            where.stationTypeName = Like(`%${searchParams.stationTypeName}%`);
        }
        if (searchParams.dataTypeCode) {
            where.dataTypeCode = Like(`%${searchParams.dataTypeCode}%`);
        }
        if (searchParams.dataTypeName) {
            where.dataTypeName = Like(`%${searchParams.dataTypeName}%`);
        }

        const options: FindManyOptions<StationType> = {
            where,
            skip: (pageNum - 1) * pageSize,
            take: pageSize,
            order: { createdAt: 'DESC' }
        };

        const [entities, total] = await this.stationTypeRepository.findAndCount(options);
        const list = entities.map(entity => this.toResponseDTO(entity));

        return {
            list,
            total,
            pageNum,
            pageSize,
            totalPages: Math.ceil(total / pageSize)
        };
    }

    /**
     * 查询所有测站类型
     */
    async findAll(): Promise<StationTypeResponseDTO[]> {
        const entities = await this.stationTypeRepository.find({
            order: { createdAt: 'DESC' }
        });
        return entities.map(entity => this.toResponseDTO(entity));
    }

    /**
     * 更新测站类型
     */
    async update(id: string, updateDto: UpdateStationTypeDTO): Promise<StationTypeResponseDTO> {
        // 检查记录是否存在
        const existingEntity = await this.stationTypeRepository.findOne({ where: { id } });
        if (!existingEntity) {
            throw new BusinessException(`测站类型 ID ${id} 不存在`, 'STATION_TYPE_NOT_FOUND');
        }

        // 如果更新编码，检查新编码是否已被其他记录使用
        if (updateDto.stationTypeCode && updateDto.stationTypeCode !== existingEntity.stationTypeCode) {
            const codeExists = await this.checkCodeExists(updateDto.stationTypeCode, id);
            if (codeExists) {
                throw new BusinessException(`测站类型编码 ${updateDto.stationTypeCode} 已存在`, 'STATION_TYPE_CODE_EXISTS');
            }
        }

        await this.stationTypeRepository.update(id, updateDto);
        const updatedEntity = await this.stationTypeRepository.findOne({ where: { id } });
        return this.toResponseDTO(updatedEntity!);
    }

    /**
     * 删除测站类型
     */
    async delete(id: string): Promise<boolean> {
        const result = await this.stationTypeRepository.delete(id);
        return result.affected! > 0;
    }

    /**
     * 批量删除测站类型 - 修复版本
     */
    async batchDelete(ids: string[]): Promise<number> {
        if (ids.length === 0) {
            return 0;
        }

        try {
            // 使用Repository的manager进行事务
            return await this.stationTypeRepository.manager.transaction(async (transactionalEntityManager: EntityManager) => {
                const repository = transactionalEntityManager.getRepository(StationType);
                const result = await repository.delete(ids);
                return result.affected || 0;
            });
        } catch (error) {
            // 如果事务失败，尝试直接删除
            console.warn('Transaction failed, trying direct delete:', error.message);
            const result = await this.stationTypeRepository.delete(ids);
            return result.affected || 0;
        }
    }

    /**
     * 检查编码是否存在
     */
    async checkCodeExists(stationTypeCode: string, excludeId?: string): Promise<boolean> {
        const queryBuilder = this.stationTypeRepository.createQueryBuilder('stationType')
            .where('stationType.stationTypeCode = :stationTypeCode', { stationTypeCode });

        if (excludeId) {
            queryBuilder.andWhere('stationType.id != :excludeId', { excludeId });
        }

        const count = await queryBuilder.getCount();
        return count > 0;
    }

    /**
     * 转换为响应 DTO
     */
    private toResponseDTO(entity: StationType): StationTypeResponseDTO {
        return {
            id: entity.id,
            stationTypeCode: entity.stationTypeCode,
            stationTypeName: entity.stationTypeName,
            dataTypeCode: entity.dataTypeCode,
            dataTypeName: entity.dataTypeName,
            originalColumnName: entity.originalColumnName,
            originalColumnNumber: entity.originalColumnNumber,
            createdAt: entity.createdAt,
            updatedAt: entity.updatedAt
        };
    }
}

/**
 * 测站信息管理服务
 */
@Provide()
export class StationInfoService {
    @InjectEntityModel(StationInfo)
    stationInfoRepository: Repository<StationInfo>;

    @InjectDataSource()
    dataSource: DataSource;

    /**
     * 创建测站信息
     */
    async create(createDto: CreateStationInfoDTO): Promise<StationInfoResponseDTO> {
        // 验证地理坐标
        this.validateCoordinates(createDto.lon, createDto.lat);

        // 检查测站编码是否已存在
        const existingStation = await this.findByStcd(createDto.stcd);
        if (existingStation) {
            throw new BusinessException(`测站编码 ${createDto.stcd} 已存在`, 'STATION_CODE_EXISTS');
        }

        const entity = this.stationInfoRepository.create(createDto);
        const savedEntity = await this.stationInfoRepository.save(entity);
        return this.toResponseDTO(savedEntity);
    }

    /**
     * 根据ID查询测站信息
     */
    async findById(id: string): Promise<StationInfoResponseDTO | null> {
        const entity = await this.stationInfoRepository.findOne({ where: { id } });
        return entity ? this.toResponseDTO(entity) : null;
    }

    /**
     * 根据测站编码查询
     */
    async findByStcd(stcd: string): Promise<StationInfoResponseDTO | null> {
        const entity = await this.stationInfoRepository.findOne({ where: { stcd } });
        return entity ? this.toResponseDTO(entity) : null;
    }

    /**
     * 分页查询测站信息
     */
    async findPage(queryDto: QueryStationInfoDTO): Promise<PageResultDTO<StationInfoResponseDTO>> {
        const { pageNum = 1, pageSize = 10, ...searchParams } = queryDto;

        const queryBuilder = this.stationInfoRepository.createQueryBuilder('station');

        // 添加基础查询条件
        if (searchParams.stcd) {
            queryBuilder.andWhere('station.stcd LIKE :stcd', {
                stcd: `%${searchParams.stcd}%`
            });
        }
        if (searchParams.stnm) {
            queryBuilder.andWhere('station.stnm LIKE :stnm', {
                stnm: `%${searchParams.stnm}%`
            });
        }
        if (searchParams.source) {
            queryBuilder.andWhere('station.source LIKE :source', {
                source: `%${searchParams.source}%`
            });
        }
        if (searchParams.stationTypeCode) {
            queryBuilder.andWhere('station.stationTypeCode = :stationTypeCode', {
                stationTypeCode: searchParams.stationTypeCode,
            });
        }

        // 添加地理位置范围条件
        if (searchParams.minLon !== undefined && searchParams.maxLon !== undefined) {
            queryBuilder.andWhere('station.lon BETWEEN :minLon AND :maxLon', {
                minLon: searchParams.minLon,
                maxLon: searchParams.maxLon
            });
        }
        if (searchParams.minLat !== undefined && searchParams.maxLat !== undefined) {
            queryBuilder.andWhere('station.lat BETWEEN :minLat AND :maxLat', {
                minLat: searchParams.minLat,
                maxLat: searchParams.maxLat
            });
        }

        // 分页和排序
        queryBuilder
            .skip((pageNum - 1) * pageSize)
            .take(pageSize)
            .orderBy('station.createdAt', 'DESC');

        const [entities, total] = await queryBuilder.getManyAndCount();
        const list = entities.map(entity => this.toResponseDTO(entity));

        return {
            list,
            total,
            pageNum,
            pageSize,
            totalPages: Math.ceil(total / pageSize)
        };
    }

    /**
     * 查询所有测站信息
     */
    async findAll(): Promise<StationInfoResponseDTO[]> {
        const entities = await this.stationInfoRepository.find({
            order: { createdAt: 'DESC' }
        });
        return entities.map(entity => this.toResponseDTO(entity));
    }

    /**
     * 根据地理位置范围查询测站
     */
    async findByLocation(minLon: number, maxLon: number, minLat: number, maxLat: number): Promise<StationInfoResponseDTO[]> {
        const entities = await this.stationInfoRepository.createQueryBuilder('station')
            .where('station.lon BETWEEN :minLon AND :maxLon', { minLon, maxLon })
            .andWhere('station.lat BETWEEN :minLat AND :maxLat', { minLat, maxLat })
            .getMany();

        return entities.map(entity => this.toResponseDTO(entity));
    }

    /**
     * 更新测站信息
     */
    async update(id: string, updateDto: UpdateStationInfoDTO): Promise<StationInfoResponseDTO> {
        // 验证地理坐标
        this.validateCoordinates(updateDto.lon, updateDto.lat);

        // 检查记录是否存在
        const existingEntity = await this.stationInfoRepository.findOne({ where: { id } });
        if (!existingEntity) {
            throw new BusinessException(`测站信息 ID ${id} 不存在`, 'STATION_NOT_FOUND');
        }

        // 如果更新测站编码，检查新编码是否已被其他记录使用
        if (updateDto.stcd && updateDto.stcd !== existingEntity.stcd) {
            const codeExists = await this.checkStcdExists(updateDto.stcd, id);
            if (codeExists) {
                throw new BusinessException(`测站编码 ${updateDto.stcd} 已存在`, 'STATION_CODE_EXISTS');
            }
        }

        await this.stationInfoRepository.update(id, updateDto);
        const updatedEntity = await this.stationInfoRepository.findOne({ where: { id } });
        return this.toResponseDTO(updatedEntity!);
    }

    /**
     * 删除测站信息
     */
    async delete(id: string): Promise<boolean> {
        const result = await this.stationInfoRepository.delete(id);
        return result.affected! > 0;
    }

    /**
     * 批量删除测站信息 - 修复版本
     */
    async batchDelete(ids: string[]): Promise<number> {
        if (ids.length === 0) {
            return 0;
        }

        try {
            return await this.stationInfoRepository.manager.transaction(async (transactionalEntityManager: EntityManager) => {
                const repository = transactionalEntityManager.getRepository(StationInfo);
                const result = await repository.delete(ids);
                return result.affected || 0;
            });
        } catch (error) {
            console.warn('Transaction failed, trying direct delete:', error.message);
            const result = await this.stationInfoRepository.delete(ids);
            return result.affected || 0;
        }
    }

    /**
     * 检查测站编码是否存在
     */
    async checkStcdExists(stcd: string, excludeId?: string): Promise<boolean> {
        const queryBuilder = this.stationInfoRepository.createQueryBuilder('station')
            .where('station.stcd = :stcd', { stcd });

        if (excludeId) {
            queryBuilder.andWhere('station.id != :excludeId', { excludeId });
        }

        const count = await queryBuilder.getCount();
        return count > 0;
    }

    /**
     * 批量导入测站信息 - 修复版本
     */
    async batchImport(stationInfoList: CreateStationInfoDTO[]): Promise<StationInfoResponseDTO[]> {
        // 验证输入数据
        if (!stationInfoList || stationInfoList.length === 0) {
            throw new BusinessException('导入数据不能为空', 'IMPORT_DATA_EMPTY');
        }

        // 验证每个测站的地理坐标
        stationInfoList.forEach((station, index) => {
            try {
                this.validateCoordinates(station.lon, station.lat);
            } catch (error) {
                throw new BusinessException(`第${index + 1}条数据坐标无效: ${error.message}`, 'INVALID_COORDINATES');
            }
        });

        // 检查重复的测站编码
        const stcds = stationInfoList.map(item => item.stcd);
        const duplicateStcds = stcds.filter((stcd, index) => stcds.indexOf(stcd) !== index);
        if (duplicateStcds.length > 0) {
            throw new BusinessException(`导入数据中存在重复的测站编码: ${duplicateStcds.join(', ')}`, 'DUPLICATE_STCD');
        }

        // 检查数据库中是否已存在
        const existingStations = await this.stationInfoRepository
            .createQueryBuilder('station')
            .where('station.stcd IN (:...stcds)', { stcds })
            .getMany();

        if (existingStations.length > 0) {
            const existingStcds = existingStations.map(station => station.stcd);
            throw new BusinessException(`数据库中已存在测站编码: ${existingStcds.join(', ')}`, 'STCD_EXISTS');
        }

        // 使用Repository的manager进行事务
        try {
            return await this.stationInfoRepository.manager.transaction(async (transactionalEntityManager: EntityManager) => {
                const repository = transactionalEntityManager.getRepository(StationInfo);
                const entities = repository.create(stationInfoList);
                const savedEntities = await repository.save(entities);
                return savedEntities.map(entity => this.toResponseDTO(entity));
            });
        } catch (error) {
            // 如果事务失败，尝试直接保存
            console.warn('Transaction failed, trying direct save:', error.message);
            const entities = this.stationInfoRepository.create(stationInfoList);
            const savedEntities = await this.stationInfoRepository.save(entities);
            return savedEntities.map(entity => this.toResponseDTO(entity));
        }
    }

    /**
     * 验证地理坐标
     */
    private validateCoordinates(lon?: number, lat?: number): void {
        if (lon !== undefined && (lon < -180 || lon > 180)) {
            throw new BusinessException('经度必须在-180到180之间', 'INVALID_LONGITUDE');
        }
        if (lat !== undefined && (lat < -90 || lat > 90)) {
            throw new BusinessException('纬度必须在-90到90之间', 'INVALID_LATITUDE');
        }
    }

    /**
     * 转换为响应 DTO
     */
    private toResponseDTO(entity: StationInfo): StationInfoResponseDTO {
        return {
            id: entity.id,
            stcd: entity.stcd,
            stnm: entity.stnm,
            lon: entity.lon,
            lat: entity.lat,
            source: entity.source,
            geo: entity.geo,
            // 新增
            stationTypeCode: entity.stationTypeCode,
            createdAt: entity.createdAt,
            updatedAt: entity.updatedAt
        };
    }
}

/**
 * 监测数据管理 Service - 完整版
 * 支持 dataTypes 多选功能
 */

@Provide()
export class MonitoringDataService {
    @InjectEntityModel(MonitoringData)
    monitoringDataRepository: Repository<MonitoringData>;

    // 模拟其他服务的依赖注入，实际项目中应该注入真实的服务
    // @Inject()
    // stationTypeService: StationTypeService;
    // @Inject()
    // stationInfoService: StationInfoService;

    private dataTypeNameCache = new Map<string, string>();
    private stationNameCache = new Map<string, string>();
    private stationTypeNameCache = new Map<string, string>();

    /**
     * 刷新数据类型名称缓存
     */
    private async refreshDataTypeNameCache() {
        // 实际项目中从 stationTypeService 获取数据
        // const stationTypes = await this.stationTypeService.findAll();
        this.dataTypeNameCache.clear();
        // 模拟数据
        this.dataTypeNameCache.set('water_level', '水位数据');
        this.dataTypeNameCache.set('temperature', '温度数据');
        this.dataTypeNameCache.set('humidity', '湿度数据');
    }

    /**
     * 刷新测站名称缓存
     */
    private async refreshStationNameCache() {
        // 实际项目中从 stationInfoService 获取数据
        // const stations = await this.stationInfoService.findAll();
        this.stationNameCache.clear();
        // 模拟数据
        this.stationNameCache.set('ST001', '长江1号监测站');
        this.stationNameCache.set('ST002', '长江2号监测站');
    }

    /**
     * 刷新测站类型名称缓存
     */
    private async refreshStationTypeNameCache() {
        // 实际项目中从 stationTypeService 获取数据
        // const stationTypes = await this.stationTypeService.findAll();
        this.stationTypeNameCache.clear();
        // 模拟数据
        this.stationTypeNameCache.set('ST001', '水位监测站');
        this.stationTypeNameCache.set('ST002', '气象监测站');
    }

    /**
     * 刷新所有缓存
     */
    private async refreshAllCaches() {
        await Promise.all([
            this.refreshDataTypeNameCache(),
            this.refreshStationNameCache(),
            this.refreshStationTypeNameCache()
        ]);
    }

    /**
     * 转换为响应 DTO，填充 dataTypeName、stationName、stationTypeName
     */
    private async toResponseDTOWithName(entity: MonitoringData): Promise<MonitoringDataResponseDTO> {
        // 检查缓存是否需要初始化
        if (this.dataTypeNameCache.size === 0 || this.stationNameCache.size === 0 || this.stationTypeNameCache.size === 0) {
            await this.refreshAllCaches();
        }

        const dataTypeName =
            entity.dataType && this.dataTypeNameCache.has(entity.dataType)
                ? this.dataTypeNameCache.get(entity.dataType)
                : undefined;

        const stationName =
            entity.stationCode && this.stationNameCache.has(entity.stationCode)
                ? this.stationNameCache.get(entity.stationCode)
                : undefined;

        const stationTypeName =
            entity.stationTypeCode && this.stationTypeNameCache.has(entity.stationTypeCode)
                ? this.stationTypeNameCache.get(entity.stationTypeCode)
                : undefined;

        return {
            id: entity.id,
            stationCode: entity.stationCode,
            stationName,
            dataType: entity.dataType,
            dataTypeName,
            stationTypeCode: entity.stationTypeCode,
            stationTypeName,
            monitoringDate: entity.monitoringDate,
            monitoringValue: entity.monitoringValue,
            createdAt: entity.createdAt,
            updatedAt: entity.updatedAt,
        };
    }

    /**
     * 创建监测数据
     */
    async create(createDto: CreateMonitoringDataDTO): Promise<MonitoringDataResponseDTO> {
        // 实际项目中应该验证测站类型编码和测站编码是否存在
        /*
        if (createDto.stationTypeCode) {
            const stationType = await this.stationTypeService.findByCode(createDto.stationTypeCode);
            if (!stationType) {
                throw new BusinessException(`测站类型编码 ${createDto.stationTypeCode} 不存在`, 'STATION_TYPE_NOT_FOUND');
            }
        }

        if (createDto.stationCode) {
            const station = await this.stationInfoService.findByStcd(createDto.stationCode);
            if (!station) {
                throw new BusinessException(`测站编码 ${createDto.stationCode} 不存在`, 'STATION_NOT_FOUND');
            }
        }
        */

        const entity = this.monitoringDataRepository.create(createDto);
        const savedEntity = await this.monitoringDataRepository.save(entity);
        return this.toResponseDTOWithName(savedEntity);
    }

    /**
     * 根据ID查询监测数据
     */
    async findById(id: string): Promise<MonitoringDataResponseDTO | null> {
        const entity = await this.monitoringDataRepository.findOne({ where: { id } });
        return entity ? this.toResponseDTOWithName(entity) : null;
    }

    /**
     * 分页查询监测数据 - 支持 dataTypes 多选
     */
    async findPage(queryDto: QueryMonitoringDataDTO): Promise<PageResultDTO<MonitoringDataResponseDTO>> {
        const { pageNum = 1, pageSize = 10, ...searchParams } = queryDto;

        const queryBuilder = this.monitoringDataRepository.createQueryBuilder('data');

        if (searchParams.stationCode) {
            queryBuilder.andWhere('data.stationCode LIKE :stationCode', {
                stationCode: `%${searchParams.stationCode}%`,
            });
        }

        // 数据类型查询逻辑：优先使用 dataTypes，如果没有则使用 dataType
        if (searchParams.dataTypes && searchParams.dataTypes.length > 0) {
            // 多选数据类型
            queryBuilder.andWhere('data.dataType IN (:...dataTypes)', {
                dataTypes: searchParams.dataTypes,
            });
        } else if (searchParams.dataType) {
            // 单选数据类型（保持向后兼容）
            queryBuilder.andWhere('data.dataType LIKE :dataType', {
                dataType: `%${searchParams.dataType}%`,
            });
        }

        // 测站类型编码查询条件
        if (searchParams.stationTypeCode) {
            queryBuilder.andWhere('data.stationTypeCode = :stationTypeCode', {
                stationTypeCode: searchParams.stationTypeCode,
            });
        }

        // 测站类型名称查询条件
        if (searchParams.stationTypeName) {
            queryBuilder.andWhere('data.stationTypeName LIKE :stationTypeName', {
                stationTypeName: `%${searchParams.stationTypeName}%`,
            });
        }

        // 时间范围查询
        if (searchParams.startDate && searchParams.endDate) {
            queryBuilder.andWhere('data.monitoringDate BETWEEN :startDate AND :endDate', {
                startDate: searchParams.startDate,
                endDate: searchParams.endDate,
            });
        } else if (searchParams.startDate) {
            queryBuilder.andWhere('data.monitoringDate >= :startDate', {
                startDate: searchParams.startDate,
            });
        } else if (searchParams.endDate) {
            queryBuilder.andWhere('data.monitoringDate <= :endDate', {
                endDate: searchParams.endDate,
            });
        }

        // 数值范围查询
        if (searchParams.minValue !== undefined) {
            queryBuilder.andWhere('data.monitoringValue >= :minValue', {
                minValue: searchParams.minValue,
            });
        }
        if (searchParams.maxValue !== undefined) {
            queryBuilder.andWhere('data.monitoringValue <= :maxValue', {
                maxValue: searchParams.maxValue,
            });
        }

        queryBuilder
            .skip((pageNum - 1) * pageSize)
            .take(pageSize)
            .orderBy('data.monitoringDate', 'DESC');

        const [entities, total] = await queryBuilder.getManyAndCount();

        const list = [];
        for (const entity of entities) {
            list.push(await this.toResponseDTOWithName(entity));
        }

        return {
            list,
            total,
            pageNum,
            pageSize,
            totalPages: Math.ceil(total / pageSize),
        };
    }

    /**
     * 根据测站编码查询监测数据
     */
    async findByStationCode(stationCode: string, limit?: number): Promise<MonitoringDataResponseDTO[]> {
        const queryBuilder = this.monitoringDataRepository
            .createQueryBuilder('data')
            .where('data.stationCode = :stationCode', { stationCode })
            .orderBy('data.monitoringDate', 'DESC');

        if (limit) {
            queryBuilder.limit(limit);
        }

        const entities = await queryBuilder.getMany();

        const result = [];
        for (const entity of entities) {
            result.push(await this.toResponseDTOWithName(entity));
        }

        return result;
    }

    /**
     * 根据测站类型编码查询监测数据
     */
    async findByStationTypeCode(stationTypeCode: string, limit?: number): Promise<MonitoringDataResponseDTO[]> {
        const queryBuilder = this.monitoringDataRepository
            .createQueryBuilder('data')
            .where('data.stationTypeCode = :stationTypeCode', { stationTypeCode })
            .orderBy('data.monitoringDate', 'DESC');

        if (limit) {
            queryBuilder.limit(limit);
        }

        const entities = await queryBuilder.getMany();

        const result = [];
        for (const entity of entities) {
            result.push(await this.toResponseDTOWithName(entity));
        }

        return result;
    }

    /**
     * 根据多个数据类型查询监测数据
     */
    async findByDataTypes(
        dataTypes: string[],
        stationCode?: string,
        stationTypeCode?: string,
        limit?: number
    ): Promise<MonitoringDataResponseDTO[]> {
        if (!dataTypes || dataTypes.length === 0) {
            return [];
        }

        const queryBuilder = this.monitoringDataRepository
            .createQueryBuilder('data')
            .where('data.dataType IN (:...dataTypes)', { dataTypes });

        if (stationCode) {
            queryBuilder.andWhere('data.stationCode = :stationCode', { stationCode });
        }

        if (stationTypeCode) {
            queryBuilder.andWhere('data.stationTypeCode = :stationTypeCode', { stationTypeCode });
        }

        queryBuilder.orderBy('data.monitoringDate', 'DESC');

        if (limit) {
            queryBuilder.limit(limit);
        }

        const entities = await queryBuilder.getMany();

        const result = [];
        for (const entity of entities) {
            result.push(await this.toResponseDTOWithName(entity));
        }

        return result;
    }

    /**
     * 根据时间范围查询监测数据 - 支持 dataTypes 多选
     */
    async findByDateRange(
        startDate: Date,
        endDate: Date,
        stationCode?: string,
        dataTypes?: string[],
        stationTypeCode?: string
    ): Promise<MonitoringDataResponseDTO[]> {
        const queryBuilder = this.monitoringDataRepository
            .createQueryBuilder('data')
            .where('data.monitoringDate BETWEEN :startDate AND :endDate', { startDate, endDate });

        if (stationCode) {
            queryBuilder.andWhere('data.stationCode = :stationCode', { stationCode });
        }

        // 支持多个数据类型
        if (dataTypes && dataTypes.length > 0) {
            queryBuilder.andWhere('data.dataType IN (:...dataTypes)', { dataTypes });
        }

        if (stationTypeCode) {
            queryBuilder.andWhere('data.stationTypeCode = :stationTypeCode', { stationTypeCode });
        }

        queryBuilder.orderBy('data.monitoringDate', 'DESC');

        const entities = await queryBuilder.getMany();

        const result = [];
        for (const entity of entities) {
            result.push(await this.toResponseDTOWithName(entity));
        }

        return result;
    }

    /**
     * 获取最新监测数据 - 支持多个数据类型
     */
    async findLatestData(
        stationCode?: string,
        stationTypeCode?: string,
        dataTypes?: string[],
        limit: number = 100
    ): Promise<MonitoringDataResponseDTO[]> {
        const queryBuilder = this.monitoringDataRepository.createQueryBuilder('data');

        if (stationCode) {
            queryBuilder.where('data.stationCode = :stationCode', { stationCode });
        }

        if (stationTypeCode) {
            if (stationCode) {
                queryBuilder.andWhere('data.stationTypeCode = :stationTypeCode', { stationTypeCode });
            } else {
                queryBuilder.where('data.stationTypeCode = :stationTypeCode', { stationTypeCode });
            }
        }

        // 支持多个数据类型过滤
        if (dataTypes && dataTypes.length > 0) {
            const whereMethod = stationCode || stationTypeCode ? 'andWhere' : 'where';
            queryBuilder[whereMethod]('data.dataType IN (:...dataTypes)', { dataTypes });
        }

        const entities = await queryBuilder
            .orderBy('data.monitoringDate', 'DESC')
            .limit(limit)
            .getMany();

        const result = [];
        for (const entity of entities) {
            result.push(await this.toResponseDTOWithName(entity));
        }

        return result;
    }

    /**
     * 更新监测数据
     */
    async update(id: string, updateDto: UpdateMonitoringDataDTO): Promise<MonitoringDataResponseDTO> {
        const existingEntity = await this.monitoringDataRepository.findOne({ where: { id } });
        if (!existingEntity) {
            throw new BusinessException(`监测数据 ID ${id} 不存在`, 'MONITORING_DATA_NOT_FOUND');
        }

        // 实际项目中应该验证测站类型编码和测站编码是否存在
        /*
        if (updateDto.stationTypeCode) {
            const stationType = await this.stationTypeService.findByCode(updateDto.stationTypeCode);
            if (!stationType) {
                throw new BusinessException(`测站类型编码 ${updateDto.stationTypeCode} 不存在`, 'STATION_TYPE_NOT_FOUND');
            }
        }

        if (updateDto.stationCode) {
            const station = await this.stationInfoService.findByStcd(updateDto.stationCode);
            if (!station) {
                throw new BusinessException(`测站编码 ${updateDto.stationCode} 不存在`, 'STATION_NOT_FOUND');
            }
        }
        */

        await this.monitoringDataRepository.update(id, updateDto);
        const updatedEntity = await this.monitoringDataRepository.findOne({ where: { id } });
        return this.toResponseDTOWithName(updatedEntity!);
    }

    /**
     * 删除监测数据
     */
    async delete(id: string): Promise<boolean> {
        const result = await this.monitoringDataRepository.delete(id);
        return result.affected! > 0;
    }

    /**
     * 批量删除监测数据
     */
    async batchDelete(ids: string[]): Promise<number> {
        if (ids.length === 0) {
            return 0;
        }

        try {
            return await this.monitoringDataRepository.manager.transaction(
                async (transactionalEntityManager: EntityManager) => {
                    const repository = transactionalEntityManager.getRepository(MonitoringData);
                    const result = await repository.delete(ids);
                    return result.affected || 0;
                }
            );
        } catch (error) {
            console.warn('Transaction failed, trying direct delete:', error.message);
            const result = await this.monitoringDataRepository.delete(ids);
            return result.affected || 0;
        }
    }

    /**
     * 批量导入监测数据
     */
    async batchImport(monitoringDataList: CreateMonitoringDataDTO[]): Promise<MonitoringDataResponseDTO[]> {
        if (!monitoringDataList || monitoringDataList.length === 0) {
            throw new BusinessException('导入数据不能为空', 'IMPORT_DATA_EMPTY');
        }

        // 实际项目中应该批量验证测站类型编码和测站编码
        /*
        // 批量验证测站类型编码
        const stationTypeCodes = [...new Set(monitoringDataList
            .map(item => item.stationTypeCode)
            .filter(code => code))] as string[];
        
        if (stationTypeCodes.length > 0) {
            const existingStationTypes = await this.stationTypeService.findAll();
            const existingStationTypeCodes = existingStationTypes.map(st => st.stationTypeCode);
            const invalidStationTypeCodes = stationTypeCodes.filter(code => !existingStationTypeCodes.includes(code));
            
            if (invalidStationTypeCodes.length > 0) {
                throw new BusinessException(
                    `以下测站类型编码不存在: ${invalidStationTypeCodes.join(', ')}`, 
                    'STATION_TYPE_NOT_FOUND'
                );
            }
        }

        // 批量验证测站编码
        const stationCodes = [...new Set(monitoringDataList
            .map(item => item.stationCode)
            .filter(code => code))] as string[];
        
        if (stationCodes.length > 0) {
            const existingStations = await this.stationInfoService.findAll();
            const existingStationCodes = existingStations.map(s => s.stcd);
            const invalidStationCodes = stationCodes.filter(code => !existingStationCodes.includes(code));
            
            if (invalidStationCodes.length > 0) {
                throw new BusinessException(
                    `以下测站编码不存在: ${invalidStationCodes.join(', ')}`, 
                    'STATION_NOT_FOUND'
                );
            }
        }
        */

        try {
            return await this.monitoringDataRepository.manager.transaction(
                async (transactionalEntityManager: EntityManager) => {
                    const repository = transactionalEntityManager.getRepository(MonitoringData);
                    const entities = repository.create(monitoringDataList);
                    const savedEntities = await repository.save(entities);

                    const result = [];
                    for (const entity of savedEntities) {
                        result.push(await this.toResponseDTOWithName(entity));
                    }
                    return result;
                }
            );
        } catch (error) {
            console.warn('Transaction failed, trying direct save:', error.message);
            const entities = this.monitoringDataRepository.create(monitoringDataList);
            const savedEntities = await this.monitoringDataRepository.save(entities);

            const result = [];
            for (const entity of savedEntities) {
                result.push(await this.toResponseDTOWithName(entity));
            }
            return result;
        }
    }

    /**
     * 获取数据统计信息
     */
    async getDataStatistics(stationCode: string, stationTypeCode?: string): Promise<DataStatisticsDTO> {
        const queryBuilder = this.monitoringDataRepository.createQueryBuilder('data').where(
            'data.stationCode = :stationCode',
            { stationCode }
        );

        if (stationTypeCode) {
            queryBuilder.andWhere('data.stationTypeCode = :stationTypeCode', { stationTypeCode });
        }

        const [totalCount, latestData, earliestData, avgResult, maxResult, minResult] = await Promise.all([
            queryBuilder.getCount(),
            queryBuilder.clone().orderBy('data.monitoringDate', 'DESC').getOne(),
            queryBuilder.clone().orderBy('data.monitoringDate', 'ASC').getOne(),
            queryBuilder.clone().select('AVG(data.monitoringValue)', 'avg').getRawOne(),
            queryBuilder.clone().select('MAX(data.monitoringValue)', 'max').getRawOne(),
            queryBuilder.clone().select('MIN(data.monitoringValue)', 'min').getRawOne(),
        ]);

        // 获取测站名称和测站类型名称
        let stationName: string | undefined;
        let stationTypeName: string | undefined;

        if (this.stationNameCache.size === 0) {
            await this.refreshStationNameCache();
        }
        stationName = this.stationNameCache.get(stationCode);

        if (stationTypeCode) {
            if (this.stationTypeNameCache.size === 0) {
                await this.refreshStationTypeNameCache();
            }
            stationTypeName = this.stationTypeNameCache.get(stationTypeCode);
        }

        return {
            stationCode,
            stationName,
            stationTypeCode,
            stationTypeName,
            totalCount,
            latestDate: latestData?.monitoringDate,
            earliestDate: earliestData?.monitoringDate,
            avgValue: avgResult?.avg ? Number(avgResult.avg) : undefined,
            maxValue: maxResult?.max ? Number(maxResult.max) : undefined,
            minValue: minResult?.min ? Number(minResult.min) : undefined,
        };
    }

    /**
     * 根据测站编码和数据类型获取数据统计
     */
    async getDataStatisticsByType(stationCode: string, dataType?: string, stationTypeCode?: string): Promise<DataStatisticsDTO> {
        const queryBuilder = this.monitoringDataRepository.createQueryBuilder('data').where(
            'data.stationCode = :stationCode',
            { stationCode }
        );

        if (dataType) {
            queryBuilder.andWhere('data.dataType = :dataType', { dataType });
        }

        if (stationTypeCode) {
            queryBuilder.andWhere('data.stationTypeCode = :stationTypeCode', { stationTypeCode });
        }

        const [totalCount, latestData, earliestData, avgResult, maxResult, minResult] = await Promise.all([
            queryBuilder.getCount(),
            queryBuilder.clone().orderBy('data.monitoringDate', 'DESC').getOne(),
            queryBuilder.clone().orderBy('data.monitoringDate', 'ASC').getOne(),
            queryBuilder.clone().select('AVG(data.monitoringValue)', 'avg').getRawOne(),
            queryBuilder.clone().select('MAX(data.monitoringValue)', 'max').getRawOne(),
            queryBuilder.clone().select('MIN(data.monitoringValue)', 'min').getRawOne(),
        ]);

        // 获取相关名称
        let stationName: string | undefined;
        let stationTypeName: string | undefined;

        if (this.stationNameCache.size === 0) {
            await this.refreshStationNameCache();
        }
        stationName = this.stationNameCache.get(stationCode);

        if (stationTypeCode) {
            if (this.stationTypeNameCache.size === 0) {
                await this.refreshStationTypeNameCache();
            }
            stationTypeName = this.stationTypeNameCache.get(stationTypeCode);
        }

        return {
            stationCode,
            stationName,
            stationTypeCode,
            stationTypeName,
            totalCount,
            latestDate: latestData?.monitoringDate,
            earliestDate: earliestData?.monitoringDate,
            avgValue: avgResult?.avg ? Number(avgResult.avg) : undefined,
            maxValue: maxResult?.max ? Number(maxResult.max) : undefined,
            minValue: minResult?.min ? Number(minResult.min) : undefined,
        };
    }

    /**
     * 统计所有测站数据数量
     */
    async countByStation(): Promise<{ stationCode: string; stationTypeCode?: string; count: number }[]> {
        const result = await this.monitoringDataRepository
            .createQueryBuilder('data')
            .select('data.stationCode', 'stationCode')
            .addSelect('data.stationTypeCode', 'stationTypeCode')
            .addSelect('COUNT(*)', 'count')
            .groupBy('data.stationCode')
            .addGroupBy('data.stationTypeCode')
            .getRawMany();

        return result.map((item) => ({
            stationCode: item.stationCode,
            stationTypeCode: item.stationTypeCode,
            count: Number(item.count),
        }));
    }

    /**
     * 按测站类型统计数据
     */
    async countByStationType(): Promise<{ stationTypeCode: string; stationTypeName?: string; count: number }[]> {
        const result = await this.monitoringDataRepository
            .createQueryBuilder('data')
            .select('data.stationTypeCode', 'stationTypeCode')
            .addSelect('COUNT(*)', 'count')
            .where('data.stationTypeCode IS NOT NULL')
            .groupBy('data.stationTypeCode')
            .getRawMany();

        // 填充测站类型名称
        if (this.stationTypeNameCache.size === 0) {
            await this.refreshStationTypeNameCache();
        }

        return result.map((item) => ({
            stationTypeCode: item.stationTypeCode,
            stationTypeName: this.stationTypeNameCache.get(item.stationTypeCode),
            count: Number(item.count),
        }));
    }

    /**
     * 清理过期数据
     */
    async deleteExpiredData(beforeDate: Date): Promise<number> {
        try {
            return await this.monitoringDataRepository.manager.transaction(async (transactionalEntityManager: EntityManager) => {
                const repository = transactionalEntityManager.getRepository(MonitoringData);
                const result = await repository
                    .createQueryBuilder()
                    .delete()
                    .where('monitoringDate < :beforeDate', { beforeDate })
                    .execute();

                return result.affected || 0;
            });
        } catch (error) {
            console.warn('Transaction failed, trying direct delete:', error.message);
            const result = await this.monitoringDataRepository
                .createQueryBuilder()
                .delete()
                .where('monitoringDate < :beforeDate', { beforeDate })
                .execute();
            return result.affected || 0;
        }
    }

    /**
     * 清理缓存
     */
    async clearCaches(): Promise<void> {
        this.dataTypeNameCache.clear();
        this.stationNameCache.clear();
        this.stationTypeNameCache.clear();
    }

    /**
     * 手动刷新缓存
     */
    async refreshCaches(): Promise<void> {
        await this.refreshAllCaches();
    }
}

